/**
 * JAVACC DEMO 1.0
 * @copy right dwusoft company All rights reserved. 
 * @Package com.apache.uct.service.plugins  
 */
package com.apache.uct.service.plugins;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import com.apache.api.manager.PluginConnector;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.database.constant.SystemTools;
import com.apache.database.constant.Validator;
import com.apache.rpc.util.LoadRpcService;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.entity.Act;
import com.apache.uct.common.entity.DataRight;
import com.apache.uct.common.entity.Dept;
import com.apache.uct.common.entity.Org;
import com.apache.uct.common.entity.User;
import com.apache.uct.common.vo.ActVo;
import com.apache.uct.manager.ActManager;
import com.apache.uct.manager.DataRightManager;
import com.apache.uct.manager.DeptManager;
import com.apache.uct.manager.OrgManager;
import com.apache.uct.manager.UserManager;
import com.apache.uct.util.UctStringUtil;

/**
 * description:  获取用户综合(LoginUser)信息
 * @author dwusoft 创建时间：2015-3-30  
 * @Copyright(c)2014:北京--软件技术有限公司
 */
public class UserIntegratePlugin implements PluginConnector {

	private UserManager userManager;
	private OrgManager orgManager;
	private DeptManager deptManager;
	private DataRightManager dataRightManager;
	private ActManager actManager;
	private Logger log = Logger.getLogger(UserIntegratePlugin.class);

	/**
	 * TODO 简单描述该方法的实现功能（可选）.  
	 * @see com.apache.api.manager.PluginConnector#execute(com.apache.api.vo.ParamsVo)  
	 */
	public Object execute(ParamsVo vo) throws Exception {
		String userEname = String.valueOf(vo.getParams("userEname"));
		if (Validator.isNotNull(userEname)) {
			User user = getUserByEname(userEname);
			if ("T".equals(user.getDelStatus()) || -1 == user.getUserStatus()) {//用户为删除状态
				return null;
			} else if (0 == user.getUserStatus()) {//用户为禁用状
				return null;
			}
			Org org = getOrgByOrgId(user.getOrgId());
			Dept dept = getDetpByDeptId(user.getDeptId());
			List<DataRight> dataList = getDataRights(user.getUserId());
			//List<Act> actList = getActs(user.getUserId());
			LoginUser loginUser = getLoginUser(user, org, dataList, dept);
			return loginUser;
		}
		return null;
	}

	/**
	 * description:  获取用户信息
	 */
	private User getUserByEname(String userEname) {
		ParamsVo vo = new ParamsVo();
		vo.setKey("byUserEname");
		vo.setParams("userEname", userEname);
		return (User) userManager.execute(vo);
	}

	/**
	 * description:  获取机构信息
	 */
	private Org getOrgByOrgId(String orgId) {
		if (Validator.isNull(orgId))
			return null;
		ParamsVo vo = new ParamsVo();
		vo.setInfoId(orgId);
		return (Org) orgManager.getInfoById(vo);
	}

	/**
	 * description:  获取部门信息
	 */
	private Dept getDetpByDeptId(String deptId) {
		if (Validator.isNull(deptId))
			return null;
		ParamsVo vo = new ParamsVo();
		vo.setInfoId(deptId);
		return (Dept) deptManager.getInfoById(vo);
	}

	/**
	 * description:  获取数据权限信息
	 */
	private List<DataRight> getDataRights(String userId) {
		ParamsVo vo = new ParamsVo();
		DataRight dr = new DataRight();
		dr.setUserId(userId);
		vo.setObj(dr);
		return dataRightManager.getList(vo);
	}

	/**
	 * description:  获取权限信息
	 */
	private List<ActVo> getActs(String userId) {
		ParamsVo vo = new ParamsVo();
		vo.setParams("userId", userId);
		vo.setKey("userActVoAllList");
		return (List<ActVo>) actManager.execute(vo);
	}

	private void getActMaps(String userId, LoginUser vo) {
		JSONArray jary = new JSONArray();
		Map<String, Act> actMap = new HashMap<String, Act>();
		Map<String, String> actMaps = ActCacheHelper.getInstance().getActMapByUserId(userId);
		if (null != actMaps && !actMaps.isEmpty()) {
			for (String key : actMaps.keySet()) {
				Act act = new Act();
				act.setActId(key);
				String actStr[] = actMaps.get(key).split(";");
				act.setFullEname(actStr[0]);
				if (actStr.length > 1) {
					act.setActUrl(actStr[1]);
				}
				actMap.put(act.getFullEname(), act);
				JSONObject jvo = new JSONObject();
				jvo.put("aid", act.getActId());
				jvo.put("fnm", act.getFullEname());
				jary.add(jvo);
			}
		} else {
			List<ActVo> actList = getActs(userId);
			if (!Validator.isEmpty(actList)) {
				ActCacheHelper.getInstance().writeUserActCache(userId, actList);
				for (int i = 0; i < actList.size(); i++) {
					ActVo actvo = actList.get(i);
					Act act = new Act();
					act.setActId(actvo.getActId());
					act.setFullEname(actvo.getFullEname());
					//act.setActCname(actvo.getActCname());
					if (Validator.isNotNull(actvo.getActUrl())) {
						act.setActUrl(actvo.getActUrl());
					}
					actMap.put(actvo.getFullEname(), act);
					JSONObject jvo = new JSONObject();
					jvo.put("aid", act.getActId());
					jvo.put("fnm", act.getFullEname());
					jary.add(jvo);
				}
			}
		}
		vo.setActJsonStr(jary.toString());
		vo.setActMap(actMap);
	}

	/**
	 * description:  获取客户信息
	 * @param user   
	 * @author Hou Dayu  
	 * @update 2015-12-1
	 */
	private void getCustomerInfo(LoginUser user) {
		String markCustomer = SystemTools.getInstance().getValue("customer_system_mark");
		if ("T".equals(markCustomer)) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("userId", user.getUserId());
			String sysPass = SystemTools.getInstance().getValue("push_to_dwusoft_pass");
			map.put("sysPass", sysPass);
			ResultEntity entity = LoadRpcService.service().doService("customerService", "customerBriefByuserId", "xml",
					map, null);
			if ("true".equals(entity.getResult()) && Validator.isNotNull(String.valueOf(entity.getEntity()))) {
				String customerInfo = String.valueOf(entity.getEntity());
				if (Validator.isNotNull(customerInfo)) {
					String str[] = customerInfo.split(",");
					log.info("customerInfo=" + customerInfo);
					if (str.length > 2) {
						user.setCustomerId(str[0]);
						user.setCustomerNo(str[1]);
						user.setCustomerName(str[2]);
					}
				}
			}
		}
	}

	/**
	 * description:  构建用户（LoginUser）信息
	 */
	private LoginUser getLoginUser(User user, Org org, List<DataRight> dataList, Dept dept) {
		LoginUser vo = new LoginUser();
		vo.setUser(user);
		if (org != null) {
			vo.setOrgId(org.getOrgId());
			vo.setDataDomain(org.getOrgDomain());
			vo.setOrgEname(org.getOrgEname());
			vo.setOrgCname(org.getOrgCname());
			user.setOrgEname(org.getOrgEname());
		}
		if (dept != null) {
			vo.setDeptId(user.getDeptId());
			vo.setDeptEname(dept.getDeptEname());
			vo.setDeptCname(dept.getDeptCname());
		}
		//字符串map
		//key为fullEname的act的map
		getActMaps(user.getUserId(), vo);
		//数据权限-部门
		String dataDeptIds = "";
		//数据权限-机构
		String dataOrgIds = "";
		if (!Validator.isEmpty(dataList)) {
			for (int i = 0; i < dataList.size(); i++) {
				DataRight data = dataList.get(i);
				if ("dept".equals(data.getDataName())) {
					dataDeptIds += data.getDataKey() + ",";
				} else if ("org".equals(data.getDataName())) {
					dataOrgIds += data.getDataKey() + ",";
				}
			}
		}
		vo.setDataOrgIds(dataOrgIds);
		vo.setDataDeptIds(dataDeptIds);
		vo.setVcode("");
		String sysFlag = UctStringUtil.getSysFlag(user.getSysEname(), user.getDelStatus());
		vo.setSysFlag(Validator.getDefaultStr(sysFlag, "0"));
		//getCustomerInfo(vo);//获取客户信息
		return vo;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	public void setOrgManager(OrgManager orgManager) {
		this.orgManager = orgManager;
	}

	public void setDeptManager(DeptManager deptManager) {
		this.deptManager = deptManager;
	}

	public void setDataRightManager(DataRightManager dataRightManager) {
		this.dataRightManager = dataRightManager;
	}

	public void setActManager(ActManager actManager) {
		this.actManager = actManager;
	}
}
